<template>
  <!-- 进度条组件内展示的进度百分比/纯数字/其他形式，封装了数字和百分比时的js动画效果 -->
  <span class="animate-number-business" :style="{ ...textStyle, '--d': `${animationDelay}ms` }">
    <template v-if="showContent">
      <!-- 如果展示数据是数字类型，则应用js动画 -->
      <template v-if="isNum(value)">
        <animate-number :num="value" :format="formatNum" />
      </template>
      <!-- 显示百分数 -->
      <template v-else-if="isPercentStr(value)">
        <animate-number :num="percent" :format="formatNum" />%
      </template>
      <!-- 其他显示形式的内容 -->
      <span v-else>{{ value }}</span>
    </template>
  </span>
</template>

<script>
import AnimateNumber from "./animate-number.vue";
export default {
  name: 'AnimateNumberBusiness',
  components: {
    AnimateNumber
  },
  props: {
    value: {
      type: [Number, String]
    },
    percent: {
      type: Number
    },
    animationDelay: {
      type: Number,
      default: 0
    },
    // 文字附加样式
    textStyle: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      showContent: false
    }
  },
  mounted() {
    if(this.animationDelay) {
      setTimeout(() => {
        this.showContent = true;
      }, this.animationDelay);
    } else {
      this.showContent = true;
    }
  },
  methods: {
    isNum(val) {
      return typeof(val) === 'number' && !isNaN(val);
    },
    // 匹配一个字符串是否为百分数，如20%,12.3%等
    isPercentStr(str) {
      return /^\d+(\.\d+)?%$/.test(str);
    },
    formatNum(num) {
      return num.toFixed(0);
    },
  }
}
</script>

<style lang="less" scoped>
.animate-number-business {
  display: inline-flex;
  animation: scale .5s both;
  animation-delay: var(--d, 0);
}
@keyframes scale {
  from {
    transform: scale(0.1);
  }
  to {
    transform: scale(1);
  }
}
</style>